package com.guard.aws;

import android.content.Context;
import android.util.Log;

import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttClientStatusCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttManager;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttMessageDeliveryCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttQos;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;

/**
 * @author skygge
 * @date 2022/6/30.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class AwsMQTTProxy {

    private static final String TAG = AwsMQTTProxy.class.getSimpleName();

    public static volatile AwsMQTTProxy instance = null;

    private AWSIotMqttManager mMqttManager;

    public static AwsMQTTProxy getInstance() {
        if (instance == null){
            synchronized (AwsMQTTProxy.class){
                if (instance == null){
                    instance = new AwsMQTTProxy();
                }
            }
        }
        return instance;
    }

    //TODO: 初始化MQTT
    public void initMQTT(Context context, String endpoint, String poolId, String topic) {
        mMqttManager = AWSIotMqttManager.from(
                Region.getRegion(Regions.US_WEST_2),
                AWSIotMqttManager.ClientId.fromString("test-w-ws"),
                AWSIotMqttManager.Endpoint.fromString(endpoint));
        mMqttManager.setAutoReconnect(true);
        AWSCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(context, poolId, Regions.US_WEST_2);

        mMqttManager.connect(credentialsProvider, (status, throwable) -> {
            Log.d(TAG, "MQTT-status:" + status.name());
            if(status== AWSIotMqttClientStatusCallback.AWSIotMqttClientStatus.Connected) {
                mMqttManager.subscribeToTopic(topic, AWSIotMqttQos.QOS1, (topic1, data) -> {
                    String message =  new String(data);
                    Log.d(TAG, "MQTT: 收到数据" + message);
                    AwsMQTTConnectObserver.getInstance().onMQTTReceive(message);
                });
            } else {
                AwsMQTTConnectObserver.getInstance().onMQTTDisconnect();
            }
        });
    }

    //TODO: 发送消息
    public void pushMQTTString(String topic, String message, AwsMQTTPushCallback callback) {
        try {
            if (mMqttManager != null) mMqttManager.publishString(message, topic, AWSIotMqttQos.QOS1, (status, userData) -> {
                boolean result = (status == AWSIotMqttMessageDeliveryCallback.MessageDeliveryStatus.Success);
                if (callback != null) callback.onGetPushResult(result);
            }, null);
        } catch (Exception e) {
            e.printStackTrace();
            if (callback != null) callback.onGetPushResult(false);
        }
    }
}
